﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Net.Loging;
using Net.Swagger;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Net.Core.Config
{
    public static class SwaggerSetup
    {
        public static void AddAdminSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var apiName = "系统管理端";
            //注册Swagger生成器
            services.AddSwaggerGen((s) =>
            {             
                try
                {

                    //遍历出全部的版本，做文档信息展示
                    typeof(CustomApiVersion.ApiVersions).GetEnumNames().ToList().ForEach(version =>
                    {
                        //s.SwaggerDoc(version, new OpenApiInfo
                        //{
                        //    Version = version,
                        //    Title = $"{apiName} 接口文档",
                        //    Description = $"{apiName} HTTP API " + version,
                        //    Contact = new OpenApiContact { Name = apiName, Email = "chenshibao@milliquad.com", Url = new Uri("https://CoreCms.Net") },
                        //});
                        //s.OrderActionsBy(o => o.RelativePath);

                        s.SwaggerDoc("v1", new OpenApiInfo
                        {
                            Version = "v1",
                            Title = "系统管理端 API",
                            Description = "系统管理端 HTTP API v1"
                        });

                    });


                    //生成API XML文档
                    var basePath = AppContext.BaseDirectory;
                    var xmlPath = Path.Combine(basePath, "doc.xml");
                    s.IncludeXmlComments(xmlPath);

                    // 开启加权小锁
                    s.OperationFilter<AddResponseHeadersFilter>();
                    s.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                    // 在header中添加token，传递到后台
                    s.OperationFilter<SecurityRequirementsOperationFilter>();

                    // 必须是 oauth2
                    s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                        Name = "Authorization",//jwt默认的参数名称
                        In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                        Type = SecuritySchemeType.ApiKey,
                        //Scheme = "Bearer",
                        //BearerFormat = "JWT"
                    });


                    ////Bearer 的scheme定义
                    //var securityScheme = new OpenApiSecurityScheme()
                    //{
                    //    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    //    Name = "Authorization",
                    //    //参数添加在头部
                    //    In = ParameterLocation.Header,
                    //    //使用Authorize头部
                    //    Type = SecuritySchemeType.Http,
                    //    //内容为以 bearer开头
                    //    Scheme = "bearer",
                    //    BearerFormat = "JWT"
                    //};
                    ////把所有方法配置为增加bearer头部信息
                    //var securityRequirement = new OpenApiSecurityRequirement
                    //{
                    //    {
                    //            new OpenApiSecurityScheme
                    //            {
                    //                Reference = new OpenApiReference
                    //                {
                    //                    Type = ReferenceType.SecurityScheme,
                    //                    Id = "bearerAuth"
                    //                }
                    //            },
                    //            new string[] {}
                    //    }
                    //};

                    ////注册到swagger中
                    //s.AddSecurityDefinition("bearerAuth", securityScheme);
                    //s.AddSecurityRequirement(securityRequirement);

                }
                catch (Exception ex)
                {
                    NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Swagger, "Swagger", "Swagger生成失败，Doc.xml丢失，请检查并拷贝。", ex);
                }

            });
        } 
    }
}
